package com.lvy.hczn.front.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lvy.hczn.front.business.common.CacheConstants;
import com.lvy.hczn.front.business.common.Constants;
import com.lvy.hczn.front.business.service.PurchaseOrderDetailService;
import com.lvy.hczn.front.common.core.redis.RedisCache;
import com.lvy.hczn.front.system.domain.business.DeliveryOrder;
import com.lvy.hczn.front.business.mapper.DeliveryOrderMapper;
import com.lvy.hczn.front.business.service.DeliveryOrderService;
import com.lvy.hczn.front.system.domain.business.PurchaseOrderDetail;
import com.lvy.hczn.front.system.domain.business.UpOrDownPolicy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class DeliveryOrderServiceImpl extends ServiceImpl<DeliveryOrderMapper, DeliveryOrder> implements DeliveryOrderService {

    @Autowired
    private DeliveryOrderMapper deliveryOrderMapper;

    @Autowired
    private PurchaseOrderDetailService purchaseOrderDetailService;

    @Autowired
    private RedisCache redisCache;

    /**
     * @Description 大件商品采购入库状态处理
     * @Param
     * @Author yw
     * @Date 2024/6/27 15:36
     * @Return
     **/
    @Override
    public void updateByEntry(UpOrDownPolicy upOrDownPolicy) {
        DeliveryOrder deliveryOrder = super.getOne(Wrappers.<DeliveryOrder>lambdaQuery().eq(DeliveryOrder::getDeliveryOrderCode, upOrDownPolicy.getDeliveryOrderCode()));
        if (deliveryOrder != null) {
            String key = CacheConstants.REDIS_KEY_SOCKET_CLIENT + ":" + upOrDownPolicy.getClientId() + ":deliverOrderCode";
            if (!deliveryOrder.getStatus().equals(Constants.DELIVERY_ORDER_STATUS_ZERO) && redisCache.get(key) == null) {
            } else {
                LambdaUpdateWrapper<PurchaseOrderDetail> purchaseDetailWrapper = new LambdaUpdateWrapper<>();
                purchaseDetailWrapper.eq(PurchaseOrderDetail::getBoxCode, upOrDownPolicy.getBoxCode()).eq(PurchaseOrderDetail::getPurchaseOrderCode, upOrDownPolicy.getDeliveryOrderCode()).set(PurchaseOrderDetail::getStatus, Constants.ENTRY_ED);
                purchaseOrderDetailService.update(purchaseDetailWrapper);

                if (!deliveryOrder.getStatus().equals(Constants.DELIVERY_ORDER_STATUS_ONE)) {
                    /*第一次入库响应，更新取货单状态为取货中**/
                    deliveryOrder.setStatus(Constants.DELIVERY_ORDER_STATUS_ONE);
                    super.updateById(deliveryOrder);
                }
            }
        }
    }
}
